﻿
namespace BeepMaker
{
    using System.IO;
    using System.Media;
    using System;
    public class Beeper
    {
        private static Beeper singleton;
        
        public static Beeper Singleton
        {
            get { return singleton; }
        }

        public int Amplitude {get; set;}
        public int Frequency {get; set;}
        public int Duration {get; set;}

        public void Beep()
        {
            Beep(Amplitude, Frequency, Duration, SP);
        }

        static Beeper()
        {
            singleton = new Beeper();
        }

        public SoundPlayer SP;

        public static void Beep(int ampl, int freq, int duration, SoundPlayer SP)
        {
            double a = ((ampl * 32768.0) / 1000.0) - 1.0;
            double deltaFT = (2 * Math.PI * freq) / 44100.0;
            int samples = (44100 * duration) / 1000;
            int bytes = samples * 4;
            int[] hfr = new int[] { 0x46464952, 0x24 + bytes, 0x45564157, 0x20746d66, 0x10, 0x20001, 0xac44, 0x2b110, 0x100004, 0x61746164, bytes };
            using (MemoryStream ms = new MemoryStream(0x24 + bytes))
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    int length = hfr.Length - 1;
                    for (int I = 0; I <= length; I++)
                    {
                        bw.Write(hfr[I]);
                    }
                    int sample = samples - 1;
                    for (int T = 0; T <= sample; T++)
                    {
                        short Sample = (short)Math.Round((double)(a * Math.Sin(deltaFT * T)));
                        bw.Write(Sample);
                        bw.Write(Sample);
                    }
                    bw.Flush();
                    ms.Seek(0L, SeekOrigin.Begin);
                    using (SP = new SoundPlayer(ms))
                    {
                        SP.PlaySync();
                    }
                }
            }
        }
    }
}
